<?php

namespace pmvc\mvc\controller;

use pmvc\mvc\Controller;
use pmvc\mvc\Dispatcher;
use pmvc\mvc\Model;

use Exception;

class ExceptionController
	implements Controller {

	private $exception;
	private $showErrorDetails		= TRUE;
	private $preserveOutputBuffer	= FALSE;

	public function __construct(Exception $exception=NULL) {
		$this->exception = $exception;
	}
	
	/**
	 * {@inheritDoc}
	 */
    public function handleRequest(Model $model, Dispatcher $dispatcher) {
    	header("HTTP/1.0 500 Internal Server Error");
    	if (!pmvc_hasVal($this->exception) && array_key_exists("exception", $model)) {
    		$this->exception = $model["exception"];
    	}

    	$errorDetails = "";
    	if ($this->showErrorDetails) {
	    	$errorDetails = "Following are the details:
	            </p>
	            <p>
	            	<b>Code</b>: ".$this->exception->getCode()."<br/>
	            	<b>Message</b>: ".$this->exception->getMessage()."<br/>
	            	<b>File</b>: ".$this->exception->getFile()."<br/>
	            	<b>Line</b>: ".$this->exception->getLine()."<br/>
	            	<b>Trace</b>:<br><pre>".$this->exception->getTraceAsString()."</pre><br/>";
    	}

    	if (!$this->preserveOutputBuffer) {
    		$dispatcher->clearOutputStream();
    	}
    	
    	fwrite($dispatcher->getOutputStream(),"
	    	<html>
	    	    <head>
	    	        <title>Internal Server Error: ".$this->exception->getMessage()."</title>
	    	    </head>
		        <body>
		            <h1>An error occured while handling your request.</h1>
		            <p>
		                The page that you have requestd (".$dispatcher->getRequestedUrl().")
		                has resulted in an error. ".$errorDetails."
		            </p>
		        </body>
	    	</html>
    	");
    }

    public function setShowErrorDetails($showErrorDetails) {
    	$this->showErrorDetails = $showErrorDetails;
    }

    public function setPreserveOutputBuffer($preserveOutputBuffer) {
    	$this->preserveOutputBuffer = $preserveOutputBuffer;
    }
	
}

?>